import { DownloadPackageCommand } from "@src/services/client";
import clientInstance from "@src/services/instance";
import {
  FcForm,
  FcFormItem,
  FcFormSubmit,
  FcSelect,
  FormControl,
  FormField,
  IFormInstance,
  Loading,
} from "solid-fire-controls";
import { Component, createMemo, createResource, createSignal } from "solid-js";
import toast from "solid-toast";

export interface DownloadPackageProps {
  packageId?: string;
  packageSourceName?: string;
}

const DownloadPackage: Component<DownloadPackageProps> = (props) => {
  const load = (req: { id?: string; source?: string }) =>
    req.id && req.source
      ? clientInstance.package
          .getAllVersions(req.id, req.source)
          .catch((err) => {
            toast.error(err.message);
            return [];
          })
      : Promise.resolve([] as string[]);

  const req = createMemo(() => {
    return {
      id: props.packageId,
      source: props.packageSourceName,
    };
  });

  const [versionList, { mutate, refetch }] = createResource(req, load);
  const [downloading, setDownloading] = createSignal(false);
  const [form, setForm] = createSignal<IFormInstance | undefined>(undefined);
  const versions = createMemo(() => {
    return [
      { value: null, label: "请选择要下载的版本！" },
      ...(versionList() ?? [])?.map((v) => {
        return { value: v, label: v };
      }),
    ];
  });

  const handleDownload = (version: string) => {
    setDownloading(true);
    clientInstance.package
      .downloadPackage(
        new DownloadPackageCommand({
          packageId: props.packageId,
          packageSourceName: props.packageSourceName,
          packageVersion: version,
        })
      )
      .then(() => {
        toast.success("下载成功！");
      })
      .catch((err) => toast.error(err.message))
      .finally(() => setDownloading(false));
  };

  return (
    <Loading show={versionList.loading || downloading()}>
      <FcForm onRef={setForm} onSubmit={handleDownload}>
        <FcFormItem label=" ">
          <FormControl
            control={FcSelect}
            controlProps={{
              options: versions(),
            }}
          ></FormControl>
        </FcFormItem>
        <FcFormItem>
          <FcFormSubmit>下载</FcFormSubmit>
        </FcFormItem>
      </FcForm>
    </Loading>
  );
};

export default DownloadPackage;
